<template>
  <div class="login-container">
    <Particle></Particle>
    <el-card class="login-card">
      <div class="login-content">
        <!-- Left Side - Image -->
        <div class="login-image">
          <img :src="require('@/assets/bg/song_2666922424.jpg')" alt="Login Image" />
        </div>

        <!-- Right Side - Login Form -->
        <el-form v-if="isLoginPage" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
          autocomplete="on" label-position="left">
          <div class="title-container">
            <h1 class="title">欢迎使用 <span class="highlight">Rain软件授权系统</span></h1>
            <p style="color: gray; padding-bottom: 100px;">欢迎回来，请先登录</p>
          </div>
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名" name="username" type="text"
              tabindex="1" autocomplete="on" />
          </el-form-item>
          <el-tooltip v-model="capsTooltip" content="大写锁定已开启" placement="right" manual>
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
                placeholder="输入你的密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
                @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>

          <div class="button-group">
            <el-button :loading="loading" type="primary" @click="switchToRegister"
              style="background-color: rgb(206, 231, 255); border-color: rgb(206, 231, 255); color: rgb(0, 153, 255);">注册</el-button>
            <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin">登陆</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  validUsername
} from '@/utils/validate'
import { Message } from 'element-ui'
import Particle from '@/components/Particle'
export default {
  name: 'Login',
  components: { Particle },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'));
      } else if (value.length < 6 || !/[a-zA-Z]/.test(value) || !/\d/.test(value)) {
        callback(new Error('密码长度必须大于6，并且包含字母和数字'));
      } else {
        callback();
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{
          required: true,
          trigger: 'blur',
          validator: validateUsername
        }],
        password: [{
          required: true,
          trigger: 'blur',
          validator: validatePassword
        }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      isLoginPage: true
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const {
        key
      } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              Message({
                message: '登录成功, 2秒后跳转',
                type: 'success',
                duration: 5 * 1000
              })
              setTimeout(() => {
                this.$router.push({
                  path: this.redirect || '/homepage',
                  query: this.otherQuery
                });
              }, 2000);
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    switchToRegister() {
      this.$router.push('/register')
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #d1d1d1;
$light_gray: #3f3f3f;
$cursor: #3f3f3f;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 30px;
    width: 80%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 30px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.05);
    border-radius: 5px;
    color: #7e7e7e;
  }
}
</style>

<style lang="scss" scoped>
$bg: #fff;
$dark_gray: #585858;
$light_gray: #dadada;

.highlight {
  color: #205781;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  justify-content: center;
  align-items: center;
  display: flex;

  .login-form {
    position: relative;
    width: 50%;
    max-width: 100%;
    padding: 0px 0px 0;
    padding-left: 5%;
    margin: auto auto;
  }

  .button-group {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    padding: 0px 0px;
    padding-top: 10%;

    .el-button {
      width: 50%;
      /* Make buttons take equal space */
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #272727;
      margin: 0px auto 0px auto;
      text-align: left;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.login-image {
  width: 45%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-image img {
  width: 115%;
  height: 115%;
  object-fit: cover;
}

.login-content {
  display: flex;
  width: 100%;
}

.login-card {
  width: 900px;
  display: flex;
  border-radius: 25px;
  overflow: hidden;
  padding: 0px 0px;
  border-width: 0px;
  z-index: 1;
  transition: box-shadow 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* Soft default shadow */
}

.login-card:hover {
  box-shadow: 0 0 15px 5px #4D869C;
  /* Blue shadow effect */
}
</style>